// Copyright 2019 orivil.com. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at https://mit-license.org.

package models

import (
	"encoding/json"
	"strings"
)

type Result struct {
	Content   Content     `json:"content"`
	Status    string      `json:"status"`
	Total     interface{} `json:"total"`
	Attention Attention   `json:"attention"`
}

func UnmarshalResult(r *Result, data []byte) error {
	schema := make(map[string]interface{}, 3)
	err := json.Unmarshal(data, &schema)
	if err != nil {
		return err
	}
	res := make(map[string]interface{}, len(schema))
	for key, value := range schema {
		if str, ok := value.(string); ok {
			str = strings.TrimSpace(str)
			if strings.HasPrefix(str, "{") && strings.HasSuffix(str, "}") {
				s := make(map[string]interface{}, 3)
				err = json.Unmarshal([]byte(str), &s)
				if err != nil {
					return err
				}
				res[key] = s
			} else if strings.HasPrefix(str, "[") && strings.HasSuffix(str, "]") {
				var s []map[string]interface{}
				err = json.Unmarshal([]byte(str), &s)
				if err != nil {
					return err
				}
				res[key] = s
			} else {
				res[key] = str
			}
		} else {
			res[key] = str
		}
	}
	data, err = json.Marshal(res)
	if err != nil {
		return err
	} else {
		return json.Unmarshal(data, r)
	}
}

type Content struct {
	Weight     interface{} `json:"weight"`
	Title      string      `json:"title"`
	Img        string      `json:"img"`
	Desc       string      `json:"desc"`
	ShareTitle string      `json:"sharetitle"`
	OldImg     string      `json:"oldimg"`
	Idx        string      `json:"idx"`
	Threshold  string      `json:"threshold"`
	NewIdx     interface{} `json:"new_idx"`
}

type Attention struct {
	QRCode  string `json:"qrcode"`
	Account int    `json:"account"`
	Source  int    `json:"source"`
}
